import React, { Component } from "react";
import {
    SafeAreaView, Text, View, StyleSheet, TouchableOpacity, Image,
    Platform, DeviceEventEmitter, Switch, FlatList, ActivityIndicator
} from 'react-native';

import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, getCarRegisterDate, getMileFormat, getPriceFormat, getStoreStatus, getSaleStatus, getCheckStatus, getPurchaseType, getPerm } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import DealStatusDropdown, { dealOptions } from "./DealStatusDropdown"
import QuotationListModal from "./QuotationListModal"
import PriceStatusDropdown, { priceOptions } from "./PriceStatusDropdown";
import SortDropdown from "../car/stock/SortDropdown";
import AndroidModule from "../../utils/AndroidConnent";
import RegionPickerView from '../../components/Tool/RegionPickerView';
import NoData from '../../utils/NoData'
import AsyncImage from '../../components/image/AsyncImage'
import { CarSaleStatus, PermissionType } from '../../utils/Enum'
import AlertCommonView from "../../components/Tool/AlertCommonView";



let navigation = null

/**
 * isFranchisee：是否加盟商 0否1是
 */
export default class PreferenceCarListPage extends Component {


    constructor(props) {
        super(props);
        let priceOperatePerm = getPerm(PermissionType.Permission_EnableOfferPriceOperate)
        this.state = {
            priceOperatePerm,
            carList: [],
            isShowSortDrop: false,
            sortShowText: '排序',
            orderColumns: [],

            pageNo: 1,
            searchChannel: 'app_stock_merchant_car',
            saleStatus: '1,2,3,5',
            storeStatus: 0,
            isRefresh: false,
            showFoot: 0,
            joinQuotationCenter: -1,

            keyword: '',
            filterShowList: [],
            isReported: 0,
            mileageMin: 0,
            mileageMax: 10,
            registerDateBegin: 0,
            registerDateEnd: 8,
            carColor: '',
            carRank: '',
            gearboxType: 0,
            gearboxTypeTitle: '',
            emissionStd: 0,
            emissionStdTitle: '',
            energyType: 0,
            energyTypeTitle: '',
            brand: 0,
            series: 0,


            quotationProgressStatus: 0,
            isShowDealStatusDrop: false,
            dealStatusShowText: '处理状态',

            isShowQuotationListModal: false,
            isFranchisee: Constant.userInfo.isFranchisee ? Constant.userInfo.isFranchisee : 0,//是否加盟商 0否1是
            buyerId: Constant.userInfo.buyerId ? Constant.userInfo.buyerId : 0,

            buyerTagStatus: false,

            priceStatus: 0,//报价状态
            isShowPriceStatusDrop: false,
            priceStatusShowText: '报价状态',

            carId: '',
            clickQuotationProgressStatus: 0,
            showCityPicker: false,
            carProvince: 0,
            carCity: 0,

            // 新加的多选条件
            carColorList: [],
            carColorListPr: [],
            carRankList: [],
            carRankListPr: [],
            gearboxTypeList: [],
            gearboxTypeListPr: [],
            emissionStdList: [],
            emissionStdListPr: [],
            energyTypeList: [],
            energyTypeListPr: [],

            // 价格
            listPriceMin: 0,
            listPriceMax: 60,


            // 弹窗提示买手设置标签
            showAlertCommonView: false,
            showAlertData: {},

        };
    }

    componentDidMount() {

        this.commonEvent = DeviceEventEmitter.addListener('commonEvent', (data) => {
            console.log('commonEvent', data);
            if (data.type == 'search' && data.fromPage == 'PreferenceCarListPage') {
                let keywordObj = {
                    title: data.keyword,
                    key: 'keyword',
                    value: data.keyword
                }
                this.addFilter(keywordObj)
                this.setState({
                    keyword: data.keyword,

                }, function () {
                    this.refreshData()
                })

            } else if (data.type == 'moreFilter' && data.fromPage == 'PreferenceCarListPage') {

                this.addAllFilterShow(data)


                this.refreshData()
            } else if (data.type == 'offerPriceConfrimSuccess') {
                this.refreshData()
            }
        })

        this.selectBrandResult = DeviceEventEmitter.addListener('selectBrandResult', (result) => {

            if (result && result.from == 'PreferenceCarListPage') {
                this.formatBrand(result)
            }
        })

        this.backHome = DeviceEventEmitter.addListener('backHome', (result) => {
            if (result && result.index == 2) {
                navigation.navigate('WorkCenterPage')
            }
        })

        this.focusListener = this.props.navigation.addListener('focus', () => {

            DeviceEventEmitter.emit('homeListener', { isInHome: false, index: 2 });
        });

        let params = this.props.route.params
        if (params) {
            this.formatStatus(params)
        } else {
            this.setState({
                isRefresh: true,
            }, () => {
                this.getCarList()
            }
            )
        }

        this.checkUserIsBuyer()
    }

    componentWillUnmount() {
        if (this.commonEvent) {
            this.commonEvent.remove();
        }
        if (this.selectBrandResult) {
            this.selectBrandResult.remove();
        }
        if (this.backHome) {
            this.backHome.remove();
        }
    }

    componentDidUpdate(prevProps) {

        if (this.props.route.params !== prevProps.route.params) {
            let params = this.props.route.params
            this.formatStatus(params)
        }

    }

    formatStatus(params) {
        if (params.dealStatus) {
            this.setState({
                quotationProgressStatus: params.dealStatus,
                dealStatusShowText: dealOptions[params.dealStatus]
            }, function () {
                this.refreshData()
            })
        } else if (params.priceStatus) {
            this.setState({
                priceStatus: params.priceStatus,
                priceStatusShowText: priceOptions[params.priceStatus]
            }, function () {
                this.refreshData()
            })
        }
    }


    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'偏好车源'} hideSepLine={true} bgColor={'#ffffff'} RightButton={() => this.rightButton()}></Header>

                {this.renderFilter()}

                {this.state.filterShowList.length > 0 && this.renderFilterShow()}

                {this.renderCarList()}


                <DealStatusDropdown
                    dealStatusShowText={this.state.dealStatusShowText}
                    onSelect={(result) => {
                        console.log(result);
                        this.setState({
                            isShowDealStatusDrop: false,
                            quotationProgressStatus: result.value,
                            dealStatusShowText: result.title == '全部状态' ? '处理状态' : result.title
                        }, function () {
                            this.refreshData()
                        })
                    }}
                    visible={this.state.isShowDealStatusDrop}
                    onClose={() => {
                        this.setState({
                            isShowDealStatusDrop: false
                        })
                    }}
                    top={100}
                >

                </DealStatusDropdown>

                <PriceStatusDropdown
                    priceStatusShowText={this.state.priceStatusShowText}
                    onSelect={(result) => {
                        console.log(result);
                        this.setState({
                            isShowPriceStatusDrop: false,
                            priceStatus: result.value,
                            priceStatusShowText: result.title == '全部' ? '报价状态' : result.title
                        }, function () {
                            this.refreshData()
                        })
                    }}
                    visible={this.state.isShowPriceStatusDrop}
                    onClose={() => {
                        this.setState({
                            isShowPriceStatusDrop: false
                        })
                    }}
                    top={100}
                >

                </PriceStatusDropdown>

                {this.state.isShowQuotationListModal ?
                    <QuotationListModal
                        isRoot={true}
                        navigation={navigation}
                        visible={this.state.isShowQuotationListModal}
                        onClose={() => this.setModalVisible(false)}
                        carId={this.state.carId}
                        quotationProgressStatus={this.state.clickQuotationProgressStatus}
                    />
                    :
                    null
                }




                <SortDropdown
                    onSelect={(result) => {
                        console.log(result);
                        this.setState({
                            isShowSortDrop: false,
                            orderColumns: result.value,
                            sortShowText: result.title == '默认排序' ? '排序' : result.title
                        }, function () {
                            this.refreshData()
                        })
                    }}
                    visible={this.state.isShowSortDrop}
                    onClose={() => {
                        this.setState({
                            isShowSortDrop: false
                        })
                    }}
                    isShowLookCount={true}
                    top={100}
                >

                </SortDropdown>

                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false
                        })
                    }}
                    selectArea={(item) => {
                        console.log(item);
                        let address = item.provinceName + item.cityName
                        let addressObj = {
                            title: address,
                            key: 'address',
                            value: address
                        }
                        this.addFilter(addressObj)
                        this.setState({
                            showCityPicker: false,
                            carProvince: item.provinceId,
                            carCity: item.cityId
                        }, function () {
                            this.refreshData()
                        })
                    }}
                />


                {/* 弹窗提示 */}
                {
                    this.state.showAlertCommonView ?
                        <AlertCommonView
                            title={this.state.showAlertData.title}
                            content={this.state.showAlertData.content}
                            cancelBtnText={this.state.showAlertData.cancelBtnText}
                            sureBtnText={this.state.showAlertData.sureBtnText}
                            cancelHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                            }}
                            sureHandler={() => {
                                this.setState({
                                    showAlertCommonView: false
                                })
                                if (this.state.showAlertData.type === 'setTag') {
                                    navigation.navigate('BuyerSetLabelPage');
                                }
                            }}
                        />
                        :
                        null
                }


            </View>
        );
    }

    setModalVisible(visible) {
        this.setState({
            isShowQuotationListModal: visible
        })
    }


    rightButton = () => {
        return (
            <View style={styles.topRightContain}>  
                <TouchableOpacity
                    style={{ marginLeft: 8 }}
                    onPress={() => { navigation.navigate('SearchPage', { fromPage: 'PreferenceCarListPage' }) }}>
                    <Image style={styles.iconImg} source={require('source/image/comm/icon_search_black.png')}></Image>
                </TouchableOpacity>

                {/*<TouchableOpacity*/}
                {/*    style={{ marginLeft: 8 }}*/}
                {/*    onPress={() => {*/}
                {/*        navigation.navigate('OrderListPage')*/}
                {/*    }}>*/}
                {/*    <Image style={styles.iconImg} source={require('source/image/car/icon_order.png')}></Image>*/}
                {/*</TouchableOpacity>*/}

                {this.state.buyerId > 0 && (
                    <TouchableOpacity
                        style={{ marginLeft: 10 }}
                        onPress={() => {
                            navigation.navigate('BuyerSetLabelPage');
                        }}>
                        <Image style={styles.iconImg} source={require('source/image/edit_car_icon.png')}></Image>
                    </TouchableOpacity>
                )}
            </View>
        )
    }

    renderFilter() {
        return (
            <View style={styles.filterContain}>
                {this.state.isFranchisee == 0 ?
                    <TouchableOpacity
                        style={styles.filterItem}
                        onPress={() => {
                            this.setState({
                                showCityPicker: true
                            })
                        }}>
                        <Text style={styles.filterText}>城市</Text>
                        <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                    </TouchableOpacity>
                    : null
                }



                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        let params = { selectLevel: 2, from: 'PreferenceCarListPage' }
                        AndroidModule.selectBrand(params, (error, result) => {
                            console.log('result = ', result)
                            this.formatBrand(result)
                        })
                    }}>
                    <Text style={styles.filterText}>品牌</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
                {this.state.isFranchisee == 1 ?
                    <TouchableOpacity
                        style={styles.filterItem}
                        onPress={() => {
                            this.setState({
                                isShowPriceStatusDrop: true
                            })
                        }}>
                        <Text style={this.state.priceStatus ? styles.filterSelText : styles.filterText}>{this.state.priceStatusShowText}</Text>
                        <Image style={styles.filterImg} source={this.state.priceStatus ? require('source/image/comm/up_small_yeoolow.png') : require('source/image/comm/down_small_gray.png')}></Image>
                    </TouchableOpacity>
                    :
                    null
                }

                {this.state.isFranchisee == 0 ?
                    <TouchableOpacity
                        style={styles.filterItem}
                        onPress={() => {
                            this.setState({
                                isShowDealStatusDrop: true
                            })
                        }}>
                        <Text style={this.state.quotationProgressStatus ? styles.filterSelText : styles.filterText}>{this.state.dealStatusShowText}</Text>
                        <Image style={styles.filterImg} source={this.state.quotationProgressStatus ? require('source/image/comm/up_small_yeoolow.png') : require('source/image/comm/down_small_gray.png')}></Image>
                    </TouchableOpacity>
                    :
                    null
                }


                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        this.setState({
                            isShowSortDrop: true
                        })
                    }}>
                    <Text style={this.state.orderColumns.length > 0 ? styles.filterSelText : styles.filterText} numberOfLines={1}>{this.state.sortShowText}</Text>
                    <Image style={styles.filterImg} source={this.state.orderColumns.length > 0 ? require('source/image/comm/up_small_yeoolow.png') : require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.filterItem}
                    onPress={() => {
                        navigation.navigate('MoreFilterPage', {
                            fromPage: 'PreferenceCarListPage',
                            isReported: this.state.isReported,
                            mileageMin: this.state.mileageMin,
                            mileageMax: this.state.mileageMax,
                            registerDateBegin: this.state.registerDateBegin,
                            registerDateEnd: this.state.registerDateEnd,

                            listPriceMin: this.state.listPriceMin,
                            listPriceMax: this.state.listPriceMax,

                            carColorList: this.state.carColorList,
                            carRankList: this.state.carRankList,
                            gearboxTypeList: this.state.gearboxTypeList,
                            emissionStdList: this.state.emissionStdList,
                            energyTypeList: this.state.energyTypeList,
                        })
                    }}>
                    <Text style={styles.filterText}>更多</Text>
                    <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                </TouchableOpacity>
            </View>
        )
    }

    formatBrand(result) {
        if (result.brandId == 0 || !result || Object.keys(result).length == 0) {
            this.removeBrand()
        } else {
            let brandObj = {
                title: result.brandName,
                key: 'brand',
                value: result.brandId
            }
            this.addFilter(brandObj)

            if (result.seriesId == 0 || !result.seriesId) {
                this.removeSeriesBrand()
            } else {
                let seriesObj = {
                    title: result.seriesName,
                    key: 'series',
                    value: result.seriesId
                }
                this.addFilter(seriesObj)
            }

        }
        this.setState({
            brand: result.brandId,
            series: result.seriesId,
        }, function () {
            this.refreshData()
        })

    }

    removeBrand() {
        let temp = []
        for (let i = 0; i < this.state.filterShowList.length; i++) {
            if (this.state.filterShowList[i].key != 'brand' && this.state.filterShowList[i].key != 'series') {
                temp.push(this.state.filterShowList[i])

            }
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        })
    }

    removeSeriesBrand() {
        let temp = []
        for (let i = 0; i < this.state.filterShowList.length; i++) {
            if (this.state.filterShowList[i].key != 'series') {
                temp.push(this.state.filterShowList[i])

            }
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        })
    }

    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()

                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)

                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    renderCarList() {
        return (
            <FlatList
                data={this.state.carList}
                renderItem={this.state.isFranchisee == 1 ? this.renderFranchiseeCarItem.bind(this) : this.renderCarItem.bind(this)}
                keyExtractor={item => item.carId + ''}
                style={{ flex: 1 }}
                extraData={this.state}
                ListFooterComponent={this._renderFooter.bind(this)}
                ListEmptyComponent={this.renderEmpty.bind(this)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={0.2}
                onRefresh={this.refreshData}
                refreshing={this.state.isRefresh}
            />
        )
    }

    clearFilterShow() {
        this.setState({
            keyword: '',
            filterShowList: [],
            isReported: 0,
            mileageMin: 0,
            mileageMax: 10,
            registerDateBegin: 0,
            registerDateEnd: 8,
            carColor: '',
            carRank: '',
            gearboxType: 0,
            emissionStd: 0,
            energyType: 0,
            brand: 0,
            series: 0,
            carProvince: 0,
            carCity: 0,
            // 多选
            carColorList: [],
            carRankList: [],
            gearboxTypeList: [],
            emissionStdList: [],
            energyTypeList: [],
            listPriceMin: 0,
            listPriceMax: 60,
        }, function () {
            this.refreshData()
        })
    }

    removeFilterShow(item, index) {
        console.log('removeFilterShow', item)
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i != index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key == 'keyword') {
            this.setState({
                keyword: ''
            })
        }

        else if (item.key == 'isReported') {
            this.setState({
                isReported: 0
            })
        }
        else if (item.key == 'mileage') {
            this.setState({
                mileageMin: 0,
                mileageMax: 10
            })
        }
        else if (item.key == 'carAge') {
            this.setState({
                registerDateBegin: 0,
                registerDateEnd: 8
            })
        }
         else if (item.key == 'brand') {
            this.setState({
                brand: 0
            })
        } else if (item.key == 'series') {
            this.setState({
                series: 0
            })
        } else if (item.key == 'address') {
            this.setState({
                carProvince: 0,
                carCity: 0
            })
        }else if (item.key == 'price') {
            this.setState({
                listPriceMin: 0,
                listPriceMax: 60,
            })
        }else if(item.key == 'carColorList'){
            this.state.carColorList.map((color, index)=>{
                if(item.value == color){
                    this.state.carColorList.splice(index,1)
                }
            })
        }else if(item.key == 'carRankList'){
            this.state.carRankList.map((Rank, index)=>{
                if(item.value == Rank){
                    this.state.carRankList.splice(index,1)
                }
            })
        }else if(item.key == 'gearboxTypeList'){
            this.state.gearboxTypeList.map((gearbox, index)=>{
                if(item.value == gearbox){
                    this.state.gearboxTypeList.splice(index,1)
                }
            })
        }else if(item.key == 'emissionStdList'){
            this.state.emissionStdList.map((emission, index)=>{
                if(item.value == emission){
                    this.state.emissionStdList.splice(index,1)
                }
            })
        }else if(item.key == 'energyTypeList'){
            this.state.energyTypeList.map((energy, index)=>{
                if(item.value == energy){
                    this.state.energyTypeList.splice(index,1)
                }
            })
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshData()
        })
    }

    _onEndReached() {
        console.log('_onEndReached', this.state.showFoot)
        if (this.state.showFoot != 0) {
            return null;
        }

        let nextPage = this.state.pageNo + 1

        this.setState({ showFoot: 2, pageNo: nextPage },
            function () {
                this.getCarList();
            });


    }

    _renderFooter() {
        if (this.state.carList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(150) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    refreshData = () => {

        this.setState({ carList: [], isRefresh: true, pageNo: 1 }, function () {
            this.getCarList();
        })

    }

    // 买方
    renderCarItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CarOfferPriceDetailPage', {
                        carId: item.carId,
                        saleStatus: item.saleStatus,
                        merchantId: item.merchantId
                    })
                    // navigation.navigate('CarOfferPricePage',{carId:item.carId,merchantId:item.merchantId})
                }}
            >
                <View style={styles.itemCompanyContain}>
                    <Text style={styles.companyText}>{item.merchantAbbreviation}</Text>
                    <Text style={styles.companyText}>{this.getQuotationProgressStatus(item)}</Text>
                </View>

                <View style={{ backgroundColor: '#f6f6f6', height: 1 }}></View>

                <View style={styles.carContainer}>

                    <View style={styles.labelBox}>
                        {
                            item.detectionStatus == 3 ?
                                <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                :
                                null
                        }

                        {
                            item.isReported == 1 ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                    <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                </View>
                                :
                                null
                        }

                        {
                            item.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                    <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                </View>
                                :
                                null
                        }

                    </View>

                    <AsyncImage
                        source={{ uri: getImgUrl(item.mainPic) }}
                        defaultSource={require('source/image/icon_car_default.png')}
                        style={styles.carImage}
                        resizeMode="cover"
                    />

                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={2} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>


                        <View style={styles.priceContain}>
                            <Text style={styles.price}>挂牌价：{getPriceFormat(item.listPrice)}</Text>

                            {item.conversationQuantity && item.conversationQuantity != 0 ?
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    {/*<Image style={styles.msgCountImg} source={require('source/image/car/icon_car_msg.png')}></Image>*/}
                                    <Text style={{color: '#999999'}}>{item.conversationQuantity}人</Text>
                                </View>
                                :
                                null
                            }

                        </View>

                        <View>
                            <Text style={{fontSize: 12, color: '#999999'}}>{item.createTime}</Text>
                        </View>


                    </View>
                </View>
            </TouchableOpacity>
        )

    }

    getQuotationProgressStatus(item) {
        if (item.quotationProgressStatus == 1) {
            return (
                <View style={{flexDirection: 'row'}}>
                    {item?.timeoutTimeShowStr && (
                        <Text style={{backgroundColor: '#FFFBE8', fontSize: 12, paddingHorizontal: 5, paddingVertical: 2, borderRadius: 2, color: '#ED542E'}}>{item.timeoutTimeShowStr || ''}</Text>
                    )}
                    <Text style={{color: '#ED542E', marginLeft: 4}}>待处理</Text>
                </View>
            )
        } else if (item.quotationProgressStatus == 2) {
            return '沟通中'
        } else if (item.quotationProgressStatus == 4) {
            return '待确认'
        }
        return ''
    }

    /**
     * quotationProgressStatus：1: 无询价(平台视角描述)、未询价(卖家视角描述)、待处理(买家个人视角描述) 2：沟通中：发起过会话即算 4:待确认：发起过报价即算
     * @param {*} param0 
     * @returns 
     */
    renderFranchiseeCarItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CarOfferPriceDetailPage', {
                        carId: item.carId,
                        saleStatus: item.saleStatus,
                        merchantId: item.merchantId
                    })
                    // navigation.navigate('CarOfferPricePage',{carId:item.carId,merchantId:item.merchantId})
                }}>

                <View style={styles.carContainer}>

                    <View style={styles.labelBox}>
                        {
                            item.detectionStatus == 3 ?
                                <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                :
                                null
                        }

                        {
                            item.isReported == 1 ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                    <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                </View>
                                :
                                null
                        }

                        {
                            item.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                    <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                </View>
                                :
                                null
                        }
                    </View>

                    <AsyncImage source={{ uri: getImgUrl(item.mainPic) }} style={styles.carImage} defaultSource={require('source/image/car/car_default_list_left.png')} />


                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={1} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>

                        {item.sellerQuotationUserName && item.sellerQuotationUserName != '' ?
                            <View style={styles.followContain}>
                                <Text style={styles.checkStatusText}>跟进人：{item.sellerQuotationUserName}</Text>
                            </View>
                            : null
                        }
                        <View style={styles.priceContain}>
                            <Text style={styles.price}>挂牌价：{getPriceFormat(item.listPrice)}</Text>
                        </View>
                    </View>
                </View>

                <View style={styles.carItemBottomContain}>
                    <View style={styles.bottomLeftContain}>
                        <Image style={styles.lookImg} source={require('source/image/car/icon_look.png')}></Image>
                        <Text style={styles.lookText}>{item.pageView}</Text>
                    </View>


                    {this.state.priceOperatePerm ?
                        <View style={styles.bottomRightContain}>
                            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                <TouchableOpacity
                                    style={styles.bottomBtn}
                                    onPress={() => {
                                        this.setState({
                                            isShowQuotationListModal: true,
                                            carId: item.carId,
                                            clickQuotationProgressStatus: 2
                                        })
                                    }}>
                                    <Text style={styles.bottomBtnText}>沟通中{' ' + item.conversationQuantity}</Text>
                                </TouchableOpacity>



                            </View>
                            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                <TouchableOpacity
                                    style={styles.bottomBtn}
                                    onPress={() => {
                                        this.setState({
                                            isShowQuotationListModal: true,
                                            carId: item.carId,
                                            clickQuotationProgressStatus: 4
                                        })
                                    }}>
                                    <Text style={styles.bottomBtnText}>待确认{' ' + item.quotationQuantity}</Text>
                                </TouchableOpacity>



                            </View>


                        </View>

                        : null}

                </View>

            </TouchableOpacity>
        )

    }

    // 检查买手是否已经完善标签
    checkUserIsBuyer() {
        // 页面数据
        if(this.state.buyerId > 0){
            HttpUtils.getRequest(HttpUrls.checkHaveTage)
                .then(result => {
                    if (result && result.code == 0) {
                        // 请求成功
                        const isBuyer = result.data;
                        if (!isBuyer) {
                            // 弹窗提示
                            this.setState({
                                buyerTagStatus: true,
                                showAlertData: {
                                    title: '请先设置您的收车偏好~',
                                    cancelBtnText: '取消',
                                    sureBtnText: '确定',
                                    type: 'setTag'
                                },
                                showAlertCommonView: true,
                            })
                        }
                    } else {
                        console.error("请求失败:", result.message);
                    }
                })
                .catch(error => {
                    console.error("请求错误:", error);
                });
        }
    };

    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {
            carInfoStr = getCarRegisterDate(item.registerDate)
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.cityName && item.cityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.cityName
            } else {
                carInfoStr = item.cityName
            }

        }

        return carInfoStr
    }

    getCarList() {

        let params = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            merchantId: Constant.userInfo.merchantId,
            joinQuotationCenter: 1,
            saleStatus: '2',

        }

        /**
         * system_car_quotation:平台查询传递
            buyer_car_quotation:买家查询传递
            seller_car_quotation:卖家查询传递
         */
        if (this.state.isFranchisee == 1) {//加盟商作为卖家
            params['searchChannel'] = 'seller_car_quotation'
        } else {//经销商作为买家
            params['searchChannel'] = 'buyer_car_quotation'
        }

        if (this.state.detectionStatus != 0) {
            params['detectionStatus'] = this.state.detectionStatus
        }

        if (this.state.orderColumns.length > 0) {
            params['orderColumns'] = this.state.orderColumns
        }

        if (this.state.keyword != '') {
            params['carName'] = this.state.keyword
        }

        if (this.state.isReported != 0) {
            params['isReported'] = this.state.isReported
        }

        if (this.state.mileageMin != 0) {
            params['mileageMin'] = this.state.mileageMin * 10000
        }
        if (this.state.mileageMax != 10) {
            params['mileageMax'] = this.state.mileageMax * 10000
        }

        if (this.state.carColor != '') {
            params['carColor'] = this.state.carColor
        }

        // 价格
        if (this.state.listPriceMin != 0) {
            params['listPriceMin'] = this.state.listPriceMin * 10000
        }
        if (this.state.listPriceMax != 60) {
            params['listPriceMax'] = this.state.listPriceMax * 10000
        }

        // 外观颜色
        if(this.state.carColorList && this.state.carColorList.length > 0){
            params['carColorList'] = this.state.carColorList
        }
        // 车型级别
        if(this.state.carRankList && this.state.carRankList.length > 0){
            params['carRankList'] = this.state.carRankList
        }
        // 变速箱
        if(this.state.gearboxTypeList && this.state.gearboxTypeList.length > 0){
            params['gearboxTypeList'] = this.state.gearboxTypeList
        }
        // 排放标准
        if(this.state.emissionStdList && this.state.emissionStdList.length > 0){
            params['emissionStdList'] = this.state.emissionStdList
        }
        // 能源类型
        if(this.state.energyTypeList && this.state.energyTypeList.length > 0){
            params['energyTypeList'] = this.state.energyTypeList
        }

        let nowDate = new Date()
        let nowYear = nowDate.getFullYear()
        let nowMonth = nowDate.getMonth() + 1
        let nowDay = nowDate.getDate()
        if (this.state.registerDateBegin != 0) {
            let beginDate = (nowYear - this.state.registerDateBegin) + '-' + nowMonth + '-' + nowDay
            params['registerDateEnd'] = beginDate
        }
        if (this.state.registerDateEnd != 8) {
            let endDate = (nowYear - this.state.registerDateEnd) + '-' + nowMonth + '-' + nowDay
            params['registerDateBegin'] = endDate
        }

        if (this.state.quotationProgressStatus != 0 || this.state.priceStatus != 0) {
            if (this.state.isFranchisee == 1) {
                params['quotationProgressStatus'] = this.state.priceStatus
            } else {
                params['quotationProgressStatus'] = this.state.quotationProgressStatus
            }

        }

        if (this.state.brand != 0) {
            params['brand'] = this.state.brand
        }

        if (this.state.series != 0) {
            params['series'] = this.state.series
        }

        // if (this.state.carProvince != 0) {
        //     params['carProvince'] = this.state.carProvince

        // }
        if (this.state.carCity != 0) {
            let cityCode = this.state.carCity + ''
            let cityCodeStr = cityCode.substring(0, 4)
            params['areaCode'] = cityCodeStr
            // params['carCity'] = this.state.carCity
        }

        // 偏好车源
        params['isBuyerPreference'] = 1

        HttpUtils.postRequest(HttpUrls.searchCars, params)
            .then((result) => {

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList
                    console.log('resultList', resultList[1])
                    if (resultList.length > 0) {


                        if (resultList.length < 20) {

                            this.setState({
                                showFoot: 1
                            })
                        } else {
                            this.setState({
                                showFoot: 0
                            })
                        }

                        this.setState({
                            carList: this.state.carList.concat(resultList),
                        })

                    } else {

                        this.setState({
                            showFoot: 1
                        })
                    }

                    this.setState({
                        isRefresh: false,

                    })
                } else {
                    this.setState({
                        isRefresh: false,

                    })
                }
            })
            .catch((error) => {
                this.setState({
                    isRefresh: false,

                })
            });
    }

    addFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)

        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }

            if (isExist) {

            } else {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
                // filterShowList.push(filterModel)
            }
        }
        console.log('filterShowList', filterShowList)
        this.setState({
            filterShowList: filterShowList
        })
    }

    addAllFilterShow(data) {
        let tempList = []
        let resultList = []
        let isReported = data.isReported

        if (isReported == 1) {
            tempList.push({
                title: '有维保',
                key: 'isReported',
                value: 1
            })
        }

        let mileShowText = data.mileShowText
        let mileageMin = data.mileageMin
        let mileageMax = data.mileageMax

        if (mileShowText === '不限') {

        } else {
            tempList.push({
                title: mileShowText,
                key: 'mileage',
                value: 0
            })
        }

        let ageShowText = data.ageShowText
        let registerDateBegin = data.registerDateBegin
        let registerDateEnd = data.registerDateEnd

        if (ageShowText === '不限') {

        } else {
            tempList.push({
                title: ageShowText,
                key: 'carAge',
                value: 0
            })
        }

        // 价格
        let priceShowText = data.priceText
        let listPriceMin = data.listPriceMin
        let listPriceMax = data.listPriceMax
        if(priceShowText === '不限'){

        }else {
            tempList.push({
                title: priceShowText,
                key: 'price',
                value: 0
            })
        }

        // 颜色
        if(data.carColorList && data.carColorList.length > 0){
            data.carColorList.map((item, index) => {
                let tempListItem = {
                    title: item,
                    key: 'carColorList',
                    value: item
                }
                tempList.push(tempListItem)
            })
        }
        // 车型级别
        if(data.carRankList && data.carRankList.length > 0){
            data.carRankList.map((item, index) => {
                data.carRankListPr.map( rankItem => {
                    if(rankItem.id == item){
                        let tempListItem = {
                            title: rankItem.title,
                            key: 'carRankList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 变速箱
        if(data.gearboxTypeList && data.gearboxTypeList.length > 0){
            data.gearboxTypeList.map((item, index) => {
                data.gearboxTypeListPr.map(gItem => {
                    if(gItem.id == item){
                        let tempListItem = {
                            title: gItem.title,
                            key: 'gearboxTypeList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 排放标准
        if(data.emissionStdList && data.emissionStdList.length > 0){
            data.emissionStdList.map((item, index) => {
                data.emissionStdListPr.map(gItem => {
                    if(gItem.id == item){
                        let tempListItem = {
                            title: gItem.title,
                            key: 'emissionStdList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }
        // 燃油类型
        if(data.energyTypeList && data.energyTypeList.length > 0){
            data.energyTypeList.map((item, index) => {
                data.energyTypeListPr.map(rItem => {
                    if(rItem.id == item){
                        let tempListItem = {
                            title: rItem.title,
                            key: 'energyTypeList',
                            value: item
                        }
                        tempList.push(tempListItem)
                    }
                })
            })
        }


        let filterShowList = this.state.filterShowList
        if (filterShowList.length == 0) {
            resultList = tempList
        } else {
            let temp = [];
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == 'keyword' || filterShowList[i].key == 'brand') {
                    temp.push(filterShowList[i])

                }
            }
            resultList = temp.concat(tempList)

        }

        resultList.push({ key: 'clear' })

        this.setState({
            isReported: isReported,
            filterShowList: resultList,
            mileageMin: mileageMin,
            mileageMax: mileageMax,
            registerDateBegin: registerDateBegin,
            registerDateEnd: registerDateEnd,

            listPriceMin: listPriceMin,
            listPriceMax: listPriceMax,

            carColorList: data.carColorList,
            carColorListPr: data.carRankListPr,
            carRankList: data.carRankList,
            carRankListPr: data.carRankListPr,
            gearboxTypeList: data.gearboxTypeList,
            gearboxTypeListPr: data.gearboxTypeListPr,
            emissionStdList: data.emissionStdList,
            emissionStdListPr: data.emissionStdListPr,
            energyTypeList: data.energyTypeList,
            energyTypeListPr: data.energyTypeListPr,
        })
    }


};


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },
    topRightContain: {
        paddingRight: 12,
        width: '100%',
        height: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    iconImg: {
        width: 22,
        height: 22
    },
    filterContain: {
        width: '100%',
        height: 46,
        backgroundColor: '#fff',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 5,
    },

    filterItem: {
        flex: 1,
        marginHorizontal: 2,
        height: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    filterImg: {
        width: 20,
        height: 20,
    },
    filterText: {
        fontSize: 14,
        color: '#666666'
    },
    filterSelText: {
        fontSize: 14,
        color: '#F99802'
    },
    shareContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        height: 40,
        paddingHorizontal: 15
    },
    totalText: {
        fontSize: 14,
        color: '#666666'
    },
    shareBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#F99802',
        height: 30,
        paddingHorizontal: 15,
        borderRadius: 4
    },
    shareText: {
        fontSize: 12,
        color: '#fff'
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 10,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 12,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 12,
        height: 12,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 15,
        height: 15,
        marginRight: 2,
        resizeMode: 'contain'
    },

    cardContainer: {
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingBottom: 15,
        marginTop: 10,
        flexDirection: 'column',
        width: '100%',
    },
    itemCompanyContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        height: 44,
        alignItems: 'center'
    },
    companyText: {
        fontSize: 14,
        color: '#333333'
    },
    carContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    carImage: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f5f5f5',
    },
    infoContainer: {
        flex: 1,
        marginLeft: 10,
        height: 90,
        flexDirection: 'column',
        justifyContent: 'space-between',
    },
    carName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 5,
        color: '#333',
    },
    subInfo: {
        fontSize: 12,
        color: '#999999',
        marginTop: 3,
    },
    price: {
        fontSize: 14,
        color: '#ED542E',

    },
    msgCountImg: {
        width: 20,
        height: 20
    },
    priceContain: {
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    checkStatusText: {
        fontSize: 12,
        color: '#222222'
    },

    followContain: {
        // height:21,
        alignItems: 'center',
        flexDirection: 'row',
        backgroundColor: '#f4f4f4',
        borderRadius: 4,
        paddingHorizontal: 6,
        paddingVertical: 5,
    },

    carItemBottomContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    bottomLeftContain: {
        flexDirection: 'row',
        alignItems: 'center',
    },

    lookImg: {
        width: 26,
        height: 18,
        resizeMode: 'contain'
    },
    lookText: {
        fontSize: 14,
        color: '#666666'
    },

    bottomRightContain: {
        marginTop: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    bottomText: {
        fontSize: 12,
        color: '#999999'
    },
    bottomBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',

        width: 86,
        height: 32,

        borderRadius: 70,
        borderWidth: 1,
        borderColor: '#E5E5E5',
        marginRight: 10
    },
    bottomBtnText: {
        fontSize: 14,
        color: '#333333'
    },
    itemMsgNum: {
        width: 16,
        height: 16,
        borderRadius: 16,
        backgroundColor: '#ED542E',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'absolute',
        top: 3,
        right: 10
    },
    msgNumText: {
        fontSize: 9,
        color: '#fff'
    },


    labelBox: {
        zIndex: 1000,
        position: 'absolute',
        left: 4,
        top: 4,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    labelItemBox: {
        marginRight: 4,
        paddingHorizontal: 6,
        height: 18,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 10,
        color: '#FF7B00'
    },
})